<template>
  <div class="page-index">
    <div class="page-index__content scroll-box">
      <el-form :model="ruleForm" ref="ruleFormRef" :rules="rules" label-width="150px" :disabled="disabledFlag">
        <div class="content-title">
          <i class="el-icon-document"></i>
          活动基本信息
        </div>

        <div class="content-form">
          <el-form-item label="活动名称" prop="activityName">
            <el-input v-model="ruleForm.activityName" type="text"></el-input>
          </el-form-item>
          <el-form-item label="活动有效期" prop="activityTime">
            <el-date-picker v-model="ruleForm.activityTime" type="datetimerange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="现金券使用截至时间" prop="cashDeadline">
            <el-date-picker v-model="ruleForm.cashDeadline" type="datetime" placeholder="选择日期时间" style="width: 100%;"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="活动规则" prop="activityRule">
            <el-input v-model="ruleForm.activityRule" type="textarea" placeholder="请输入活动规则" resize="vertical"
              :autosize="true">
            </el-input>
          </el-form-item>
          <el-form-item label="活动背景图" prop="activityImg">
            <el-upload :action="action" list-type="picture-card" :limit="1" :on-preview="handlePictureCardPreview"
              :on-success="upLoadPic" accept="image/*" :on-change="handleImgChange" :file-list="imgList"
              :headers="headers">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="免费抽奖次数" prop="activityLimit">
            <el-input type="number" v-model="ruleForm.activityLimit" :step="1" :min="0" style="width: 100%;"
              placeholder="请输入免费抽奖次数" />
          </el-form-item>
        </div>

        <div class="content-title">
          <i class="el-icon-document"></i>
          奖品信息
        </div>

        <el-form-item label-width="0px" prop="promotionActivityPrizeConfigDTOList">
          <el-table :data="ruleForm.promotionActivityPrizeConfigDTOList" style="width: 100%" border :align="'center'"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
            <el-table-column prop="prizeLevel" label="序号" width="60" :align="'center'"></el-table-column>
            <el-table-column prop="prizeLevelName" label="奖品等级" min-width="140px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.prizeLevelName"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="奖品名称" min-width="140px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.giftName"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="奖品图片" :align="'center'" min-width="135px">
              <template slot-scope="scope">
                <single-image-upload v-model="scope.row.giftPic" :imageWidth="60" :imageHeight="60" :width="'60px'"
                  :height="'60px'">
                </single-image-upload>
              </template>
            </el-table-column>
            <el-table-column label="奖品金额" min-width="140px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.cashCouponMoney" type="number" :min="0"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="prizeQuantity" label="奖品数量" min-width="140px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.prizeQuantity" type="number"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="cashCouponLimit" label="订单最低金额可用" min-width="140px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.cashCouponLimit" type="number"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="giftCount" label="单次赠送数量" min-width="140px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.giftCount" type="number"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="prizeQuantityDay" label="每日中奖上限" min-width="140px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.prizeQuantityDay" type="number"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="winningRate" label="中奖概率(%)" min-width="115px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.winningRate" type="number"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="winningQuantityDay" label="当日中奖数量" min-width="110px">
            </el-table-column>
            <el-table-column prop="surplusNum" label="剩余数量" min-width="100px">
              <template slot-scope="scope">
                {{ scope.row.winningQuantity != null || scope.row.winningQuantity != undefined ? scope.row.prizeQuantity
                  - scope.row.winningQuantity : '/' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleDelete(scope.$index, scope.row)">删除奖项</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-button class="add-prize" icon="el-icon-plus" type="primary" size="mini" @click="addPrize"
            :disabled="ruleForm.promotionActivityPrizeConfigDTOList.length >= 9">
            添加奖项
          </el-button>
        </el-form-item>

        <el-form-item label="发布状态" prop="status">
          <el-select v-model="ruleForm.status" placeholder="请选择发布状态">
            <el-option label="发布" :value="1"></el-option>
            <el-option label="不发布" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="page-index__footer">
      <el-button size="mini" @click="$router.go(-1)">返回</el-button>
      <el-button type="primary" size="mini" @click="submitForm('ruleFormRef')" :loading="loading">保存</el-button>
    </div>
  </div>
</template>

<script>
import { createActivityConfig } from "@/api/lotteryActivityset";
import singleImageUpload from '@/page/common/single-image-upload'
export default {
  components: {
    singleImageUpload
  },
  data() {
    return {
      action: `${process.env.VUE_APP_BASE_API}/api/file-service/v1/file/uploadFile`,
      headers: {
        token: localStorage.getItem('token'), //从cookie里获取token，并赋值  Authorization ，而不是token
      },
      // https://yundian-test.obs.cn-south-1.myhuaweicloud.com:443/2025%2F20250829%2Fa8c70530-8d3e-4f60-bb10-51e1ada8f112.png
      imgList: [],
      ruleForm: {
        activityType: 3,
        activityName: '',
        activityTime: [],
        cashDeadline: '',
        activityRule: '',
        activityImg: '',
        activityLimit: '',
        promotionActivityPrizeConfigDTOList: [],
        status: 1,
      },
      rules: {
        activityName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
        activityTime: [
          { type: 'array', required: true, message: '请选择活动时间', trigger: 'change | blur' },
        ],
        cashDeadline: [
          { required: true, message: '请选择提现截止时间', trigger: 'blur | change' },
        ],
        activityRule: [
          { required: true, message: '请输入活动规则', trigger: 'blur' },
        ],
        activityImg: [
          { required: true, message: '请上传活动图片', trigger: 'change' },
        ],
        activityLimit: [
          { required: true, message: '请输入免费抽奖次数', trigger: 'blur' },
        ],
        promotionActivityPrizeConfigDTOList: [
          { type: 'array', required: true, message: '请添加奖项', trigger: 'change' },
        ],
        status: [
          { required: true, message: '请选择发布状态', trigger: 'change | blur' },
        ]
      },
      detail: {},
      loading: false,
      disabledFlag: false
    }
  },
  created() {
    if (this.$route.params.row) {
      const detail = this.detail = this.$route.params.row;
      this.ruleForm.activityName = detail.activityName;
      this.ruleForm.activityTime = [detail.activityBeginTime, detail.activityEndTime];
      this.ruleForm.cashDeadline = detail.cashDeadline;
      this.ruleForm.activityType = detail.activityType;
      this.ruleForm.activityRule = detail.activityRule;
      this.ruleForm.activityImg = detail.activityImg;
      this.imgList.push({ url: detail.activityImg });
      this.ruleForm.activityLimit = detail.activityLimit;
      this.ruleForm.status = detail.status;
      this.ruleForm.promotionActivityPrizeConfigDTOList = detail.promotionActivityPrizeConfigDTOList;
    }

    if (this.$route.params.flag) {
      this.disabledFlag = true
    }
  },
  methods: {
    handlePictureCardPreview(file) {
      this.$seeImage({
        currentTarget: {
          currentSrc: file.url,
        },
      });
    },
    upLoadPic(file, fileList) {
      this.imgList = [];
      this.ruleForm.activityImg = file.result;
    },
    handleImgChange(file, fileList) {
      if (file.response) {
        this.imgList.push({
          url: file.response.result,
          status: 'finished',
        });
      }
    },

    // 几等奖的数字转换文字
    changePrizeLevel(index) {
      const numMap = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
      return `${numMap[index]}等奖`;
    },

    addPrize() {
      this.ruleForm.promotionActivityPrizeConfigDTOList.push({
        prizeLevel: this.ruleForm.promotionActivityPrizeConfigDTOList.length + 1,
        prizeLevelName: this.changePrizeLevel(this.ruleForm.promotionActivityPrizeConfigDTOList.length),
        giftName: '',
        cashCouponMoney: '',
        prizeQuantity: '',
        cashCouponLimit: '',
        giftCount: '',
        prizeQuantityDay: '',
        winningRate: '',
      })
    },

    handleDelete(index) {
      this.$confirm('确认删除吗?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success('删除成功');
        this.ruleForm.promotionActivityPrizeConfigDTOList.splice(index, 1);
      })
    },

    // 对数组中相应的字段进行验证
    hasEmptyFields(array, fields) {
      fields = [
        'giftPic', 'giftName', 'cashCouponMoney', 'prizeQuantity', 'cashCouponLimit', 'giftCount', 'prizeQuantityDay', 'winningRate'
      ];
      const greaterThanZero = [
        'prizeQuantity', 'cashCouponLimit', 'giftCount', 'prizeQuantityDay', 'winningRate'
      ];

      // 边界判断
      if (!Array.isArray(array)) return false;
      if (!Array.isArray(fields)) return false;

      // 边界判断
      if (!Array.isArray(array) || array.length === 0) {
        return false; // 没有数据，视为无错误
      }

      // 使用 for...of，可以中途 return 错误信息
      for (let i = 0; i < array.length; i++) {
        const item = array[i];

        // 确保是对象
        if (typeof item !== 'object' || item === null) {
          return `第 ${i + 1} 项数据格式错误，必须是对象`;
        }

        // 1. 检查必填字段是否为空
        for (const field of fields) {
          const value = item[field];

          if (greaterThanZero.includes(field)) {
            if (value == null || value === '' || value <= 0) {
              return `${this.changePrizeLevel(i)} 填写的奖品信息有误,请检查`;
            }
          } else {
            if (value == null || value === '') {
              return `${this.changePrizeLevel(i)} 填写的奖品信息有误,请检查`;
            }
          }
        }

        // 2. 业务逻辑校验：单次赠送数量不能大于总奖品数量
        if (item.prizeQuantity < item.giftCount) {
          return `${this.changePrizeLevel(i)} 的单次赠送数量不能大于奖品数量`;
        }
      }

      // 全部通过
      return false;
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {

          if (new Date(this.ruleForm.activityTime[1]) > new Date(this.ruleForm.cashDeadline)) {
            this.$message.error('活动结束时间不能大于现金券使用截至时间');
            return
          }

          // 验证奖品信息内容
          const validResult = this.hasEmptyFields(this.ruleForm.promotionActivityPrizeConfigDTOList);

          if (validResult) {
            this.$message.error(typeof validResult === 'string' ? validResult : '填写的奖品信息有误,请检查');
            return
          }

          const data = {
            activityBeginTime: this.ruleForm.activityTime[0],
            activityEndTime: this.ruleForm.activityTime[1],
            activityName: this.ruleForm.activityName,
            activityRule: this.ruleForm.activityRule,
            activityType: this.ruleForm.activityType,
            activityImg: this.ruleForm.activityImg,
            activityLimit: this.ruleForm.activityLimit,
            cashDeadline: this.ruleForm.cashDeadline,
            status: this.ruleForm.status,
            promotionActivityPrizeConfigDTOList: this.ruleForm.promotionActivityPrizeConfigDTOList.map(item => {
              return {
                ...item,
                giftStyle: 7,
                giftType: 2,
                giftDeliveryType: 1,
                giftProperty: 1,
                giftDesc: '现金优惠券'
              }
            }),
          }
          this.loading = true;
          if (this.detail.uuid) {
            data.uuid = this.detail.uuid
          }
          createActivityConfig(data).then(res => {
            if (res.code == 1) {
              this.$message.success('保存成功');
              this.$router.go(-1);
            } else {
              this.$message.error(res.message || '保存失败');
            }
          }).finally(() => {
            this.loading = false
          })
          // editCashPrizeConfig(data).then(res => {
          //   if (res.code == 1) {
          //     const result = res.result
          //     if (this.detail.uuid) {
          //       result.uuid = this.detail.uuid
          //     }
          //     createActivityConfig(result).then(v => {
          //       if (v.code == 1) {
          //         this.$message.success('保存成功');
          //         this.$router.go(-1);
          //       } else {
          //         this.$message.error(v.message);
          //       }
          //     }).finally(() => {
          //       this.loading = false
          //     })
          //   } else {
          //     this.$message.error(res.message);
          //     this.loading = false
          //   }
          // }).catch(() => {
          //   this.loading = false
          // })
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.content-title {
  margin-bottom: 15px;
  font-size: 20px;
  color: #000;
}

.content-form {
  width: 500px;
}

.add-prize {
  margin-top: 15px;
}
</style>